from flask import Blueprint, jsonify, request
from sqlalchemy import func
from ..models.runway import Runway
from ..models.airport import Airport
from ..models.aircraft import Aircraft
from .. import db

bp = Blueprint('runways', __name__, url_prefix='/api/runways')

@bp.route('/analysis', methods=['GET'])
def analyze_runways():
    mode = request.args.get('mode', 'before')
    aircraft_id = request.args.get('aircraft_id', type=int)
    
    if not aircraft_id:
        return jsonify({'error': '请指定飞机型号'}), 400
        
    aircraft = Aircraft.query.get_or_404(aircraft_id)
    
    # 获取所有机场及其跑道信息
    airports = Airport.query.all()
    result = []
    
    for airport in airports:
        runways_data = []
        total_window_value = 0
        
        for runway in airport.runways:
            width = runway.width
            if mode == 'after' and runway.increased_width:
                width += runway.increased_width
                
            # 计算窗格值
            N = -(-runway.length // aircraft.length)  # 向上取整
            M = -(-width // aircraft.width)  # 向上取整
            window_value = N * M
            
            runways_data.append({
                'id': runway.id,
                'name': runway.name,
                'length': runway.length,
                'width': width,
                'window_value': window_value
            })
            total_window_value += window_value
            
        result.append({
            'id': airport.id,
            'name': airport.name,
            'latitude': airport.latitude,
            'longitude': airport.longitude,
            'region': airport.region,
            'runways': runways_data,
            'total_window_value': total_window_value
        })
    
    return jsonify(result)

@bp.route('/all-airports', methods=['GET'])
def get_all_airports_with_runways():
    """获取所有机场及其跑道信息，无需分析"""
    airports = Airport.query.all()
    result = []
    
    for airport in airports:
        runways_data = []
        
        for runway in airport.runways:
            runways_data.append({
                'id': runway.id,
                'name': runway.name,
                'length': runway.length,
                'width': runway.width,
                'increased_width': runway.increased_width
            })
            
        result.append({
            'id': airport.id,
            'name': airport.name,
            'latitude': airport.latitude,
            'longitude': airport.longitude,
            'region': airport.region,
            'runways': runways_data,
            'total_window_value': 0  # 初始值为0，不进行分析
        })
    
    return jsonify(result)

@bp.route('', methods=['GET'])
def get_runways():
    runways = Runway.query.all()
    return jsonify([runway.to_dict() for runway in runways])

@bp.route('/<int:id>', methods=['GET'])
def get_runway(id):
    runway = Runway.query.get_or_404(id)
    return jsonify(runway.to_dict())

@bp.route('', methods=['POST'])
def create_runway():
    data = request.get_json()
    runway = Runway(
        airport_id=data['airport_id'],
        name=data['name'],
        length=data['length'],
        width=data['width'],
        increased_width=data.get('increased_width')
    )
    db.session.add(runway)
    db.session.commit()
    return jsonify(runway.to_dict()), 201

@bp.route('/<int:id>', methods=['PUT'])
def update_runway(id):
    runway = Runway.query.get_or_404(id)
    data = request.get_json()
    
    runway.airport_id = data.get('airport_id', runway.airport_id)
    runway.name = data.get('name', runway.name)
    runway.length = data.get('length', runway.length)
    runway.width = data.get('width', runway.width)
    runway.increased_width = data.get('increased_width', runway.increased_width)
    
    db.session.commit()
    return jsonify(runway.to_dict())

@bp.route('/<int:id>', methods=['DELETE'])
def delete_runway(id):
    runway = Runway.query.get_or_404(id)
    db.session.delete(runway)
    db.session.commit()
    return '', 204 